package com.jack.lib.ui.widget

import android.content.Context
import com.jack.lib.core.ext.MM
import android.widget.ScrollView
import android.content.res.TypedArray
import android.util.AttributeSet
import com.jack.lib.ui.R
import android.view.View.MeasureSpec
import android.view.MotionEvent
import androidx.core.widget.NestedScrollView

/**
 * 作者: jack(黄冲)
 * 邮箱: 907755845@qq.com
 * create on 2018/11/23 15:58
 */
class JScrollView @JvmOverloads constructor(
    context: Context,
    attrs: AttributeSet? = null,
    defStyleAttr: Int = 0): NestedScrollView(context, attrs, defStyleAttr) {

    private var mInterceptX = false
    private var mJMaxHeight = 0f
    private var mDownX = 0f
    private var mDownY = 0f
    private var mOnScrollListener: OnScrollListener? = null


    init {
        val typedArray = context.obtainStyledAttributes(attrs, R.styleable.JScrollView)
        mInterceptX = typedArray.getBoolean(R.styleable.JScrollView_JInterceptX, false)
        mJMaxHeight = typedArray.getDimension(R.styleable.JScrollView_JMaxHeight, 0f).MM
        typedArray.recycle()
    }

    override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
        if (mJMaxHeight != 0f) {
            val newHeightMeasureSpec = MeasureSpec.makeMeasureSpec(
                mJMaxHeight.toInt(),
                MeasureSpec.getMode(heightMeasureSpec)
            )
            super.onMeasure(widthMeasureSpec, newHeightMeasureSpec)
            return
        }
        super.onMeasure(widthMeasureSpec, heightMeasureSpec)
    }

    override fun onInterceptTouchEvent(ev: MotionEvent): Boolean {
        if (!mInterceptX) {
            return super.onInterceptTouchEvent(ev)
        }
        when (ev.action) {
            MotionEvent.ACTION_DOWN -> {
                mDownX = ev.x
                mDownY = ev.y
            }
            MotionEvent.ACTION_MOVE -> {
                val dx = Math.abs(ev.x - mDownX)
                val dy = Math.abs(ev.y - mDownY)
                if (dx > dy) {
                    return false
                }
            }
        }
        return super.onInterceptTouchEvent(ev)
    }

    interface OnScrollListener {
        fun onScroll(scrollY: Int, oldScrollY: Int)
    }

    fun setOnScrollListener(onScrollListener: OnScrollListener?) {
        mOnScrollListener = onScrollListener
    }

    override fun onScrollChanged(l: Int, t: Int, oldl: Int, oldt: Int) {
        super.onScrollChanged(l, t, oldl, oldt)
        if (mOnScrollListener != null) {
            mOnScrollListener!!.onScroll(t, oldl)
        }
    }
}